package com.wlw.eye.ui

import android.Manifest
import android.content.pm.ActivityInfo
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.graphics.BitmapFactory
import android.graphics.Typeface
import android.os.*
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.View
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.shuyu.gsyvideoplayer.utils.OrientationUtils
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer

import com.wlw.eye.R
import com.wlw.eye.mvp.model.bean.VideoBean
import com.wlw.eye.utils.*
import kotlinx.android.synthetic.main.activity_video_detail.*
import org.jetbrains.anko.async
import org.jetbrains.anko.uiThread
import zlc.season.rxdownload2.RxDownload
import java.io.FileInputStream
import java.io.FileNotFoundException

class VideoDetailActivity : AppCompatActivity() {
    companion object {
        var MSG_IMAGE_LOADED = 101
        var PERMISSION_WRITE_EXTERNAL = 100
    }

    lateinit var bean: VideoBean
    lateinit var imageView: ImageView
    private var count: Int = 0
    lateinit var orientationUtils: OrientationUtils
    //    private var handler: MyHandler = MyHandler(this)
    var isPlay = false
    var isPause = false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_video_detail)
        bean = intent.getParcelableExtra("data")
        initView()
        prepareVideo()
    }

    private fun initView() {
        val bgUrl = bean.blurred
        bgUrl.let { ImageLoadUtils.displayHigh(this, iv_bottom_bg, bgUrl.toString()) }
        tv_video_desc.text = bean.description
        val typeface = Typeface.createFromAsset(assets, "fonts/FZLanTingHeiS-DB1-GB-Regular.TTF")
        tv_video_desc.typeface = typeface
        tv_video_title.text = bean.title
        tv_video_title.typeface = typeface
        val category = bean.category
        val duration = bean.duration
        val minute = duration?.div(60)
        val second = duration?.minus((minute?.times(60)) as Long)
        val realMinute = if (minute!! < 10) "0$minute" else minute.toString()
        val realSecond = if (second!! < 10) "0$second" else second.toString()
        tv_video_time.text = "$category/$realMinute'$realSecond''"
        tv_video_favor.text = bean.collect.toString()
        tv_video_share.text = bean.share.toString()
        tv_video_reply.text = bean.reply.toString()

        count = SPUtils.getInstance(this, "downloads").getInt("count")
        count = if (count != -1) count.inc() else 1
        tv_video_download.setOnClickListener {
            val url = bean.playUrl?.let { it1 -> SPUtils.getInstance(this, "downloads").getString(it1) }
            if (url.equals("")) {
                SPUtils.getInstance(this, "downloads").put("count", count)
                ObjectSaveUtils.saveObject(this, "download$count", bean)
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    var checkPermission = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    if (checkPermission != PackageManager.PERMISSION_GRANTED) {
                        requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), PERMISSION_WRITE_EXTERNAL)
                    } else {
                        addMission(bean.playUrl, count)
                    }
                } else {
                    addMission(bean.playUrl, count)
                }

            } else {
                showToast("该视频已经缓存过了")
            }
        }
    }

    private fun addMission(playUrl: String?, count: Int) {
        RxDownload.getInstance(this).serviceDownload(playUrl, "download$count").subscribe({ status ->
            showToast("开始下载")
            Log.e("status", status.toString())
            SPUtils.getInstance(this, "downloads").put(bean.playUrl.toString(), bean.playUrl.toString())
            SPUtils.getInstance(this, "download_state").put(playUrl.toString(), true)
        }, { showToast("下载失败") })
    }

    private fun prepareVideo() {
        val uri = intent.getStringExtra("localFile")
        if (uri != null) {
            Log.e("uri", uri)
            gsy_player.setUp(uri, false, null, null)
        } else {
            gsy_player.setUp(bean.playUrl, false, null, null)
        }
        imageView = ImageView(this)
        imageView.scaleType = ImageView.ScaleType.CENTER_CROP
        async {
            val future = Glide.with(this@VideoDetailActivity)
                    .load(bean.feed)
                    .downloadOnly(100, 100)
            val mPath = future.get().absolutePath
            uiThread {
                var mIs: FileInputStream
                try {
                    mIs = FileInputStream(mPath)
                    var bitmap = BitmapFactory.decodeStream(mIs)
                    imageView.setImageBitmap(bitmap)
                    gsy_player.thumbImageView = imageView
                } catch (e: FileNotFoundException) {
                    Log.e("FileNotFoundException", e.toString())
                }
            }
        }
        gsy_player.titleTextView.visibility = View.GONE
        gsy_player.backButton.visibility = View.VISIBLE
        orientationUtils = OrientationUtils(this, gsy_player)
        gsy_player.setIsTouchWiget(true)
        gsy_player.isRotateViewAuto = false
        gsy_player.isLockLand = false
        gsy_player.isShowFullAnimation = true
        gsy_player.isNeedLockFull = true
        gsy_player.fullscreenButton.setOnClickListener {
            orientationUtils.resolveByClick()
            gsy_player.startWindowFullscreen(this, true, true)

        }
        gsy_player.setStandardVideoAllCallBack(object :VideoListener(){
            override fun onPrepared(url: String?, vararg objects: Any?) {
                super.onPrepared(url, *objects)
                orientationUtils.isEnable = true
                isPlay = true
            }

            override fun onQuitFullscreen(url: String?, vararg objects: Any?) {
                super.onQuitFullscreen(url, *objects)
                orientationUtils.backToProtVideo()
            }
        })
        gsy_player.setLockClickListener { _, lock ->
            orientationUtils.isEnable = !lock
        }
        gsy_player.backButton.setOnClickListener {
            onBackPressed()
        }

    }

    override fun onBackPressed() {
        orientationUtils.let {
            orientationUtils.backToProtVideo()
        }
        if (StandardGSYVideoPlayer.backFromWindowFull(this)) return

        //释放所有
        gsy_player.setVideoAllCallBack(null)
        StandardGSYVideoPlayer.releaseAllVideos()
        super.onBackPressed()
    }

    override fun onResume() {
        super.onResume()
        isPause = false
        gsy_player.onVideoResume()
    }

    override fun onPause() {
        super.onPause()
        isPause = true
        gsy_player.onVideoPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        orientationUtils.releaseListener()
    }

    override fun onConfigurationChanged(newConfig: Configuration?) {
        super.onConfigurationChanged(newConfig)
        if (!isPause && isPlay) {
            if (newConfig?.orientation == ActivityInfo.SCREEN_ORIENTATION_USER) {
                if (!gsy_player.isIfCurrentIsFullscreen)
                    gsy_player.startWindowFullscreen(this, true, true)
            }
        } else {
            if (gsy_player.isIfCurrentIsFullscreen)
                StandardGSYVideoPlayer.backFromWindowFull(this)
        }
        orientationUtils.isEnable = true
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            PERMISSION_WRITE_EXTERNAL -> {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
                    addMission(bean.playUrl, count)
                else
                    showToast("未授权")
            }
        }
    }
}
